<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\AuthenticatesUsers; 
use Exception;
use Auth;
use Validator;
use Hash;
use App\User;
use App\Model\Company;
class MemberController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest', ['except' => 'logout']);
    }

    public function username()
    {
        return 'account';
    }

    public function register(Request $request)
    { 
    	// echo $request->input("password");die;
        try{
            $this->validateLogin($request);
        } catch(Exception $e) {
            return response()->json(array('message'=>$e->getMessage(), 'code'=>400), 200);
        }
        $user['account'] = $request->input("account");
        $user['password'] = bcrypt($request->input("password"));
        $user['distinguish'] = $request->input("distinguish");
        $user['name'] = $request->input("name");
        $user['state'] = 0;
        if($user['distinguish']=1){
        	$company['comName']=$user['name'];
        	$id = Company::insertGetId($company);
        	$user['companyId']=$id;
        	$zid = User::insertGetId($user);
        }else{
        	$id = User::insertGetId($user);
        } 
    	if($id){
    		return response()->json([
                'message' =>'注册成功',
                'code' => 200
            ],200);
    	}else{
    		return response()->json(array('message'=>'注册失败', 'code'=>400), 200);	
    	}
         
        
    }

    protected function validateLogin(Request $request)
    {
        $account_name = $this->username();
        $rules = [
            'account' => 'required',
            'password' => 'required',
            'name'=>'required',
            'distinguish'=>'required',
            'rpassword'=>'required'
        ];
        $messages = [
            'account.required' => '请输入账号',
            'password.required' => '请输入密码',
            'distinguish.required' => '请选择个人账号 或者企业账号',
            'name.required' => '请输入名称',
            'rpassword.required' => '请确认密码'
        ];

        $validator = Validator::make($request->all(),$rules,$messages);
        if ($validator->fails()) {
            throw new Exception($validator->errors()->first(), 1);
        }
        /*分开验证*/
        $account = $request->input($account_name);
        $password = $request->input("password");
        $rpassword = $request->input("rpassword");
        if(!preg_match('/^(?=.*[a-z]).*$/', $password)){
            throw new Exception('密码至少包含一个小写字母', 1);
        }
        if(!preg_match('/^(?=.*[A-Z]).*$/', $password)){
            throw new Exception('密码至少包含一个大写字母', 1);
        }
        if(!preg_match('/^(?=.*[0-9]).*$/', $password)){
            throw new Exception('密码至少包含一个数字', 1);
        }
        if(!preg_match('/^(?=.*[_!@#$%^&*]).*$/', $password)){
            throw new Exception('密码至少包含一个特殊字符', 1);
        }
        if(!preg_match('/^[A-Za-z0-9_!@#$%^&*]{10,}$/', $password)){
            throw new Exception('密码不能少于10位', 1);
        }


        $name = $request->input("name");
        $user = User::where($account_name,$account)->first();
        if($user) {
            throw new Exception('账号已存在', 1);
        }
        $userr = User::where('name',$name)->first();
        if($userr){
        	throw new Exception('名称已存在', 1);
        }
        if($password!=$rpassword){
        	throw new Exception('两次密码不一致', 1);
        }
        
    }

    protected function filterReturnLoginData($user)
    {
        $user = json_decode(json_encode($user), true);
        $filterFields = array("id", "name", "account", "phone", "email", "api_token", "type", "companyId", "usersignature", "distinguish", "state");
        $returnData = array();
        foreach($filterFields as $k=>$v) {
            $returnData[$v] = $user[$v];
        }
        $returnData = unsetNull($returnData);
        if(!empty($returnData['usersignature'])) {
            $http_type = ((isset($_SERVER['HTTPS'])&&$_SERVER['HTTPS']=='on')||(isset($_SERVER['HTTP_X_FORWARDED_PROTO'])&&$_SERVER['HTTP_X_FORWARDED_PROTO']=='https'))?'https://':'http://';
            $domain = $http_type.$_SERVER['HTTP_HOST'];
            $returnData['usersignature'] = $domain.$returnData['usersignature'];
        }
        return $returnData;
    }

    // 将支持的登录字段都传递到 UserProvider 进行查询
    public function credentials(Request $request)
    {
        $credentials = $request->only($this->username(), 'password' , 'type');
        return $credentials;
    }

    public function logout()
    {
        $user = Auth()->guard('api')->user();
        if($user) {
            $user->api_token = '';
            $user->save();
        }
        return response()->json(array('message'=>'退出成功', 'code'=>200), 200);
    }
}
